#include <NDL.h>
#include <SDL.h>
#include <string.h>
#include <assert.h>

static char buf[64];

#define keyname(k) #k,

#define ARRAY_LENGTH(arr) (sizeof(arr)/sizeof(arr[0]))

static const char *keyname[] = {
	"NONE",
	_KEYS(keyname)
};

static uint8_t key_state[ARRAY_LENGTH(keyname)] = { 0 };

int SDL_PushEvent(SDL_Event *event) {
	assert(0);
	return 0;
}

int process_event(SDL_Event *event) {
	if (!NDL_PollEvent(buf, sizeof(buf))) return 0;

	char* key_action = strtok(buf, " ");
	char* key_value = strtok(NULL, " ");

	if      (!strcmp(key_action, "ku")) event->type = SDL_KEYUP;
	else if (!strcmp(key_action, "kd")) event->type = SDL_KEYDOWN;
	else    assert(0);

	for (int i = 0; i < ARRAY_LENGTH(keyname); ++i) {
		if (!strcmp(keyname[i], key_value)) {
			event->key.keysym.sym = i;
			key_state[i] = (event->type==SDL_KEYDOWN) ? 1 : 0;
			break;
		}
	}
	return 1;
}

/*
 * Polls for currently pending events, and returns 1 if there are any pending events, or 0 if there are none available.
 **/
int SDL_PollEvent(SDL_Event *event) {
	return process_event(event);
}

/**
 * Waits indefinitely for the next available event, returning 1, or 0 if there was an error while waiting for events.
*/
int SDL_WaitEvent(SDL_Event *event) {
	while (!process_event(event));
	return 1;
}

int SDL_PeepEvents(SDL_Event *event, int numevents, int action, uint32_t mask) {
	assert(0);
	return 0;
}

/**
 * Gets a snapshot of the current keyboard state. 
 * The current state is return as a pointer to an array, 
 * the size of this array is stored in numkeys. 
 * The array is indexed by the SDLK_* symbols. 
 * A value of 1 means the key is pressed and a value of 0 means its not.
 * The pointer returned is a pointer to an internal SDL array and should not be freed by the caller. 
*/
uint8_t* SDL_GetKeyState(int *numkeys) {
	if (numkeys != NULL) *numkeys = ARRAY_LENGTH(key_state);
	return key_state;
}
